#include <stdlib.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#define SERVER_PORT 2356
#define MAX_LINE 1024
#define MAX_PENDING 128

char recv_buf[MAX_LINE];
char send_buf[MAX_LINE];


void *printDataFromClient(int sockfd_client)
{
    int new_fd = sockfd_client;
    memset(recv_buf, 0, sizeof(recv_buf));
    while(recv(new_fd, recv_buf, MAX_LINE, 0) > 0)
    {
        printf("Received from client:%s\n", recv_buf);
    }
}

void *sendDataToClient(int sockfd_client)
{
    int new_fd = sockfd_client;
    while(1){
        memset(send_buf, 0, sizeof(send_buf));
        gets(send_buf);
        if (!strcmp(send_buf, "quit"))
        {
	    printf("Socket end...\n");
            exit(1);
        }
        int len = send(new_fd, send_buf, sizeof(send_buf), 0);
        if (len <= 0)
        {
            exit(1);
        }
    }
}

int main()
{
    int sockfd_server;
    int sockfd_client;
    struct sockaddr_in sin, sclient;
    int sin_size;
    char buf[MAX_LINE];

    //sin初始化
    bzero((char*)&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    sin.sin_port = htons(SERVER_PORT);
    
    if ((sockfd_server = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        exit(1);
    }
    if ((bind(sockfd_server, (struct sockaddr*)&sin, sizeof(sin))) < 0)
    {
        exit(1);
    }

    //监听
    listen(sockfd_server, MAX_PENDING);
    printf("Waiting for new connection...\n");
    sin_size = sizeof(sin);
    
    //创建双线程
    pthread_t thread_1, thread_2;

    if ((sockfd_client = accept(sockfd_server, (struct sockaddr_*)(&sin), &sin_size)) < 0)
    {
        perror("accept");
        exit(1);
    }
    
    printf("A new connection occurs...\n");
    int aa = sockfd_client;
    int a = pthread_create(&thread_1, NULL, printDataFromClient, aa);
    if (a == 0)
    {
        printf("Create pthread1 successfully...\n");
    }
    int b = pthread_create(&thread_2, NULL, sendDataToClient, aa);
    if (b == 0)
    {
        printf("Create pthread2 successfully...\n");
    }
    while(recv(sockfd_client, recv_buf, MAX_LINE, 0) > 0)
    {
        printf("Server: received: %s\n", recv_buf);
    }
    
    return 0;

}
